package fr.cpe.j2ee.projet.ejb;

import java.util.ArrayList;
import java.util.Date;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;

import fr.cpe.j2ee.projet.model.Employee;

/**
 * Session Bean implementation class UserManagerSession
 */
@Stateless
@LocalBean
public class EmployeeSession extends AbstractDAO<Employee>
{
    public EmployeeSession()
    {
        super(Employee.class);
    }
    
    public Employee addUser(String email, String username, String pwd, String firstname, String lastname, int age, Date indate) throws IllegalArgumentException
    {
    	ArrayList<Object> parameters = new ArrayList<Object>();
    	parameters.add(username);
    	parameters.add(email);
    	TypedQuery<Employee> query = this.buildSelectQuery("SELECT e from Employee e WHERE e.empUsername = ?1 OR e.empEmail = ?2", parameters);

    	if(query.getResultList().size() > 0)
    	{
    		throw new IllegalArgumentException("Impossible de cr�er un nouvel employ� : le nom d'utilisateur ou l'email est d�j� utilis� !");
    	}
    	
    	Employee emp = new Employee();
    	emp.setEmpEmail(email);
    	emp.setEmpUsername(username);
    	emp.setEmpPassword(pwd);
    	emp.setEmpFirstname(firstname);
    	emp.setEmpLastname(lastname);
    	emp.setEmpAge(age);
    	emp.setEmpIndate(indate);
    	
    	this.insert(emp);
    	return emp;
    }
    
    public Employee login(String username, String password)
    {
    	ArrayList<Object> parameters = new ArrayList<Object>();
    	parameters.add(username);
    	parameters.add(password);
    	TypedQuery<Employee> query = this.buildSelectQuery("SELECT e from Employee e WHERE e.empUsername = ?1 AND e.empPassword = ?2", parameters);
    	
    	Employee emp = null;
    	
    	try
    	{
    		emp = query.getSingleResult();
    	}
    	catch(NoResultException ex)
    	{
    		// Si aucun r�sultat renvoy�.
    		emp = null;
    	}
    	
    	return emp;
    }
}
